﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;

namespace DemoDataGridToolBar
{
	public partial class ProductForm_local : System.Windows.Controls.DGTB.DataFormWindow
	{
		public ProductForm_local()
		{
			InitializeComponent();
			CancelButton.Click += new RoutedEventHandler(CancelButton_Click);
			OKButton.Click += new RoutedEventHandler(OKButton_Click);
		}

		#region - private --
		private ProductLocal _data;

		private void CopyData(ProductLocal from_, ProductLocal to_)
		{
			to_.ProductID = from_.ProductID;
			to_.ProductNumber = from_.ProductNumber;
			to_.Name = from_.Name;
			to_.Color = from_.Color;
			to_.Size = from_.Size;
			to_.Weight = from_.Weight;
			to_.StandardCost = from_.StandardCost;
			to_.ListPrice = from_.ListPrice;
			to_.SellStartDate = from_.SellStartDate;
		}

		#endregion
		#region -- override --
		
		public override void SetDataContect(object item)
		{
			this.DataContext = _data;
		}

		override public bool ValidateItem()
		{
			return !coErrorSummary.HasErrors;
		}

		override public void CancelEdit()
		{
		}

		override public object CreateNewItem()
		{
			var data = new ProductLocal();
			data.ProductID = Guid.NewGuid();
			data.SellStartDate = DateTime.Now.Date;
			_data = data;
			return data;
		}

		//public override void AddItem(Action<bool> callback)
		//{
		//  callback(true);
		//}

		public override void EditItem(object item, Action<bool> callback)
		{
			_data = new ProductLocal();
			CopyData((ProductLocal)item, _data);
			_data.OnPropertyChanged(null); // property Changed
			callback(true);
		}

		public override void SubmitChanges(bool isNewItem, Action<bool> callback)
		{
			CopyData(_data, (ProductLocal)CurrentItem);
			if(isNewItem) {
				object itemssource = null;
				if(ItemsSource is ICollectionView) {
					itemssource = ((ICollectionView)ItemsSource).SourceCollection;
				} else {
					itemssource = ItemsSource;
				}
				if(itemssource is IList) {
					var list = itemssource as IList;
					list.Add(CurrentItem);
				}
			}
			callback(true);
		}

		#endregion

		void OKButton_Click(object sender, RoutedEventArgs e)
		{
			CommitEditAndCloseWindow();
		}

		void CancelButton_Click(object sender, RoutedEventArgs e)
		{
			CancelEditAndCloseWindow();
		}
	}
}